import React, { useState, useRef } from 'react';
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip,
  Legend, ResponsiveContainer, PieChart, Pie, Cell
} from 'recharts';
import styles from './index.module.less';

const patToken = import.meta.env.VITE_API_TOKEN;
const uploadUrl = 'https://api.coze.cn/v1/files/upload';
const workflowUrl = 'https://api.coze.cn/v1/workflow/run';
const workflowId = '7540289263905603594';

export default function Data() {
  const fileInputRef = useRef(null);
  const [imgPreview, setImgPreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png');
  const [generatedImage, setGeneratedImage] = useState(null);
  const [loading, setLoading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [workflowStatus, setWorkflowStatus] = useState('');

  const userData = JSON.parse(localStorage.getItem('user')) || {};
  const user = userData.user || {};
  const data = userData.data || {};

  const weeklyCalories = data.weekly_calories || [0, 0, 0, 0, 0, 0, 0];
  const todayTraining = data.today_training || {
    "有氧运动": 0,
    "瑜伽": 0,
    "休息": 0,
    "力量训练": 0
  };
  const monthlySports = data.monthly_sports || new Array(31).fill(0);
  const totalWorkouts = monthlySports.filter(day => day === 1).length;

  const calorieData = [
    { day: '周一', calories: weeklyCalories[0] },
    { day: '周二', calories: weeklyCalories[1] },
    { day: '周三', calories: weeklyCalories[2] },
    { day: '周四', calories: weeklyCalories[3] },
    { day: '周五', calories: weeklyCalories[4] },
    { day: '周六', calories: weeklyCalories[5] },
    { day: '周日', calories: weeklyCalories[6] }
  ];

  const workoutDistribution = [
    { name: '力量训练', value: todayTraining['力量训练'] },
    { name: '有氧运动', value: todayTraining['有氧运动'] },
    { name: '瑜伽', value: todayTraining['瑜伽'] },
    { name: '休息', value: todayTraining['休息'] }
  ];

  const COLORS = ['#6a11cb', '#2575fc', '#38ef7d', '#ff6b6b'];

  const legendData = [
    { name: '力量训练', color: '#6a11cb', value: todayTraining['力量训练'] },
    { name: '有氧运动', color: '#2575fc', value: todayTraining['有氧运动'] },
    { name: '瑜伽', color: '#38ef7d', value: todayTraining['瑜伽'] },
    { name: '休息', color: '#ff6b6b', value: todayTraining['休息'] }
  ];

  const hasWorkout = (dayIndex) => {
    return monthlySports[dayIndex] === 1;
  };

  const updateImgPreview = () => {
    const file = fileInputRef.current.files[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setImgPreview(reader.result);
    };
  };

  async function uploadFile() {
    const formData = new FormData();
    const inputFile = fileInputRef.current.files[0];
    if (!inputFile) throw new Error('请选择文件');
    formData.append('file', inputFile);
    
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${patToken}` },
      body: formData
    });
    
    const ret = await res.json();
    if (ret.code !== 0) throw new Error(ret.msg || '上传失败');
    return ret.data.id;
  }

  const generate = async () => {
    setLoading(true);
    setUploadProgress(0);
    setWorkflowStatus('');

    try {
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => (prev >= 70 ? 70 : prev + 10));
      }, 300);

      setWorkflowStatus('上传文件中...');
      const file_id = await uploadFile();
      clearInterval(progressInterval);
      setUploadProgress(100);

      if (!file_id) throw new Error('上传后未返回文件 ID');

      const age = parseInt(user.age) || 18;
      const height = parseInt(user.height) || 170;

      setWorkflowStatus('调用工作流...');
      const res = await fetch(workflowUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${patToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          workflow_id: workflowId,
          parameters: {
            picture: JSON.stringify({ file_id }),
            age: age.toString(),
            height: height.toString()
          }
        })
      });

      const ret = await res.json();
      console.log('工作流完整响应:', ret);

      if (ret.code !== 0) throw new Error(ret.msg || '工作流调用失败');

      const responseData = JSON.parse(ret.data);
      const imageUrl = responseData.output;
      if (!imageUrl) throw new Error('未找到生成的图像');

      setGeneratedImage(imageUrl);
      setWorkflowStatus('生成成功！');
      
    } catch (error) {
      console.error('处理图像出错:', error);
      setWorkflowStatus(`错误: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const renderUploader = () => {
    if (generatedImage) return <img className={styles.avatarImg} src={generatedImage} alt="生成的效果图" />;
    if (imgPreview && !loading) return <img className={styles.avatarImg} src={imgPreview} alt="上传的图片" />;
    if (loading) return (
      <div className={styles.uploadProgress}>
        <div className={styles.progressText}>正在生成中，请勿关闭</div>
        <div className={styles.progressBar}>
          <div className={styles.progressFill} style={{ width: `${uploadProgress}%` }}></div>
        </div>
        {workflowStatus && <div className={styles.workflowStatus}>{workflowStatus}</div>}
      </div>
    );
    return <span style={{ color: 'white' }}>点击上传</span>;
  };

  // ------------------- 日历修改部分 -------------------
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth(); // 0-11
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
  const calendarDays = Array.from({ length: daysInMonth }, (_, i) => i + 1);
  // ----------------------------------------------------

  return (
    <div className={styles.fitnessApp}>
      <div className={styles.header}>
        <div className={styles.calendarSection}>
          <div className={styles.calendarHeader}>
            <span>{currentYear}年{currentMonth + 1}月</span>
            <span>今天</span>
          </div>
          <div className={styles.calendarGrid}>
            {['日','一','二','三','四','五','六'].map((d,i) => <div key={i} className={styles.calendarDay}>{d}</div>)}
            {calendarDays.map((day, index) => (
              <div key={index} className={`${styles.calendarDay} ${hasWorkout(index) ? styles.workoutDay : styles.restDay}`}>
                {day}
              </div>
            ))}
          </div>
        </div>

        <div className={styles.avatarSection}>
          <div className={styles.avatarUpload} onClick={() => !loading && !generatedImage && document.getElementById('fileInput').click()}>
            {renderUploader()}
          </div>
          <input
            ref={fileInputRef}
            id="fileInput"
            type="file"
            accept="image/*"
            style={{ display: 'none' }}
            onChange={updateImgPreview}
          />
          <div className={styles.uploadText}>上传图片生成理想身材</div>
          {!loading && imgPreview !== 'https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png' && (
            <button onClick={generate} className={styles.generateBtn}>
              生成效果图
            </button>
          )}
        </div>
      </div>

      <div className={styles.statsSection}>
        <div className={styles.sectionTitle}>今日训练数据</div>
        
        <div className={styles.chartContainer}>
          <div className={styles.chartTitle}>训练类型分布</div>
          <ResponsiveContainer width="100%" height={240}>
            <PieChart>
              <Pie
                data={workoutDistribution}
                cx="50%"
                cy="50%"
                innerRadius={60}
                outerRadius={80}
                fill="#8884d8"
                paddingAngle={5}
                dataKey="value"
              >
                {workoutDistribution.map((entry, index) => (
                  <Cell key={index} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip formatter={(value) => [`${value}分钟`, '训练时间']} />
            </PieChart>
          </ResponsiveContainer>
          
          <div className={styles.legendContainer}>
            {legendData.map((item, index) => (
              <div key={index} className={styles.legendItem}>
                <div className={styles.legendColor} style={{ backgroundColor: item.color }}></div>
                <span className={styles.legendText}>
                  {item.name}: {item.value}分钟
                </span>
              </div>
            ))}
          </div>
        </div>

        <div className={styles.chartContainer}>
          <div className={styles.chartTitle}>每日卡路里消耗</div>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={calorieData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="day" />
              <YAxis />
              <Tooltip formatter={(value) => [`${value}卡路里`, '消耗']} />
              <Legend />
              <Line type="monotone" dataKey="calories" stroke="#6a11cb" activeDot={{ r: 8 }} />
            </LineChart>
          </ResponsiveContainer>
        </div>

        <div className={styles.workoutStats}>
          <div className={styles.statCard}>
            <div className={styles.statLabel}>总训练次数</div>
            <div className={styles.statValue}>{totalWorkouts}</div>
            <div className={styles.statLabel}>本月已训练天数</div>
          </div>
          <div className={styles.statCard}>
            <div className={styles.statLabel}>今日总训练</div>
            <div className={styles.statValue}>
              {todayTraining['有氧运动'] + todayTraining['力量训练'] + todayTraining['瑜伽']}
            </div>
            <div className={styles.statLabel}>分钟</div>
          </div>
        </div>

        {generatedImage && (
          <>
            <div className={styles.sectionTitle}>生成的效果图</div>
            <div className={styles.imageDescription}>基于您的照片生成的理想身材效果</div>
            <img src={generatedImage} alt="生成效果" style={{ width: '100%', borderRadius: '12px', marginTop: '16px' }} />
          </>
        )}
      </div>
    </div>
  );
}
